﻿Imports System.Collections.ObjectModel
Imports System.ComponentModel
Namespace bl.bo
    Public Class genericBusinessObject
        Private _rules As List(Of Rule)
        Public Function isValid() As Boolean
            Return getBrokenRules.Count = 0
        End Function
        Public Overridable Function getErrors() As String
            Dim result As String = getErrors(String.Empty)
            If Not result Is Nothing And result.Trim().Length = 0 Then
                result = Nothing
            End If
            Return result
        End Function
        Public Overridable Function getErrors(ByVal propertyName As String) As String
            Dim result As String = String.Empty

            For Each r In getBrokenRules(propertyName)
                If propertyName = String.Empty Or propertyName = r.propertyName Then
                    result = result + r.description
                    result = result + Environment.NewLine
                End If
            Next
            result = result.Trim
            If result.Length = 0 Then
                result = Nothing
            End If
            Return result
        End Function
        Public Overridable Function getBrokenRules() As ReadOnlyCollection(Of Rule)
            Return (getBrokenRules(String.Empty))
        End Function
        Public Overridable Function getBrokenRules(ByVal propertyName As String) As ReadOnlyCollection(Of Rule)
            If (_rules Is Nothing) Then
                _rules = New List(Of Rule)
                _rules.AddRange(Me.createRules())
            End If
            Dim broken As List(Of Rule) = New List(Of Rule)

            For Each r In _rules
                If r.propertyName = propertyName Or propertyName = String.Empty Then
                    Dim isRuleBroken As Boolean = Not r.validateRule(Me)
                    Debug.WriteLine(DateTime.Now.ToLongTimeString + ": Validating the rule: '" + r.ToString + "' on object '" + Me.ToString + "'Result = '" + IIf(isRuleBroken = False, "Valid", "Broken"))
                    If isRuleBroken Then
                        broken.Add(r)
                    End If
                End If
            Next
            Return broken.AsReadOnly
        End Function

        Public Overridable Function createRules() As List(Of Rule)
            Return New List(Of Rule)
        End Function

        Public Event PropertyChanged As PropertyChangedEventHandler

        Protected Overridable Sub NotifyChanged(ByRef name As String)
            OnPropertyChanged(New PropertyChangedEventArgs(name))
            OnPropertyChanged(New PropertyChangedEventArgs("IsValid"))
        End Sub

        Protected Overridable Sub OnPropertyChanged(ByRef e As PropertyChangedEventArgs)
            RaiseEvent PropertyChanged(Me, e)
        End Sub
    End Class
End Namespace

